package cn.mymall.web.controller.houtai.menu;


import cn.mymall.constant.ResultCodeConstant;
import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.Menu;
import cn.mymall.service.IMenuService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BeanUtil;
import cn.mymall.util.DateUtil;
import cn.mymall.util.FastJsonUtil;
import cn.mymall.vo.menu.MenuReqVo;
import cn.mymall.vo.menu.MenuVo;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sky
 * @since 2021-03-11
 */
@RestController
@RequestMapping("/api/menu")
public class MenuController extends BaseHoutaiController {
    @Autowired
    private IMenuService menuService;


    @RequestMapping("/list/tree")
    public ResultCode listTree(MenuReqVo menuReqVo){
        List<Menu> myMenuList = menuService.getUserMenuList(menuReqVo.getUserId());
        List<Integer> myMenuIdList = BeanUtil.getBeanPropertyList(myMenuList,"id",true);
        List<Menu> menuList = menuService.getMenuList(menuReqVo);
        List<MenuVo> menuVoList = new ArrayList<>();
        BeanUtil.copyListProperties(menuList,menuVoList,MenuVo.class);

        List<MenuVo> parentList = new LinkedList<>();
        Map<Integer,MenuVo> parentMenuMap = new HashMap<>();
        for(MenuVo menuVo : menuVoList){
            parentMenuMap.put(menuVo.getId(),menuVo);
        }

        Map<Integer, MenuVo> parentMap = new HashMap<>();
        for(MenuVo menuVo : menuVoList){
            MenuVo parent = null;
            if(menuVo.getParentId() != null) {//子类
                if(parentMap.containsKey(menuVo.getParentId())){
                    parent = parentMap.get(menuVo.getParentId());
                }else {
                    parent = parentMenuMap.get(menuVo.getParentId());
                    if(parent == null){
                        Menu menu = menuService.getById(menuVo.getParentId());
                        parent = new MenuVo();
                        BeanUtils.copyProperties(menu,parent);
                    }
                    parent.setChildren(new LinkedList<>());
                    parentMap.put(menuVo.getParentId(),parent);
                }
                if(!parentList.contains(parent)){
                    parentList.add(parent);
                }
                parent.getChildren().add(menuVo);
            }
        }

        Collections.sort(parentList,new PropertyComparator<>("sortNum", false, true));
        Map resultMap = new HashMap();
        resultMap.put("selectIdList", myMenuIdList);
        resultMap.put("menuList",parentList);

        return ResultCode.getSuccessReturn(resultMap);
    }


    @RequestMapping("/list")
    public ResultCode list(MenuReqVo menuReqVo){
        List<Menu> menuList = menuService.getMenuList(menuReqVo);
        List<MenuVo> menuVoList = new ArrayList<>();
        BeanUtil.copyListProperties(menuList,menuVoList,MenuVo.class);

        List<MenuVo> parentList = new LinkedList<>();
        Map<Integer,MenuVo> parentMenuMap = new HashMap<>();
        for(MenuVo menuVo : menuVoList){
            parentMenuMap.put(menuVo.getId(),menuVo);
        }

        Map<Integer, MenuVo> parentMap = new HashMap<>();

        for(MenuVo menuVo : menuVoList){
            MenuVo parent = null;
            if(menuVo.getParentId() != null) {//子类
                if(parentMap.containsKey(menuVo.getParentId())){
                    parent = parentMap.get(menuVo.getParentId());
                }else {
                    parent = parentMenuMap.get(menuVo.getParentId());
                    parent.setChildren(new LinkedList<>());
                    parentMap.put(menuVo.getParentId(),parent);
                }
                parent.getChildren().add(menuVo);
            }else{//父类
                if(!parentMap.containsKey(menuVo.getId())) {
                    menuVo.setChildren(new LinkedList<>());
                    parentMap.put(menuVo.getId(), menuVo);
                    parentList.add(menuVo);
                }else{
                    parentList.add(parentMap.get(menuVo.getId()));
                }
            }
        }

        List<MenuVo> resultList = new LinkedList<>();
        for(MenuVo parent:parentList){
            resultList.add(parent);
            List<MenuVo> childList = parent.getChildren();
            if(CollectionUtils.isNotEmpty(childList)){
                resultList.addAll(childList);
            }
        }
        return ResultCode.getSuccessReturn(resultList);
    }

    @RequestMapping("/save")
    public ResultCode save(MenuReqVo reqVo){
        if(reqVo == null || checkParamsIsBlank(reqVo.getMenuName())){
            return ResultCode.getFailure(ResultCodeConstant.PARAMS_NOT_EXISTS.getCode(),ResultCodeConstant.PARAMS_NOT_EXISTS.getMessage());
        }
        Menu menu = null;
        if(reqVo.getId() != null){
            menu = menuService.getById(reqVo.getId());
        }else{
            menu = new Menu();
            menu.setStatus(StatusConstant.Y);
            menu.setAddTime(DateUtil.getCurFullTimestamp());
        }
        BeanUtils.copyProperties(reqVo, menu);
        menuService.saveOrUpdate(menu);
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/delete")
    public ResultCode delete(MenuReqVo reqVo){
        if(reqVo == null || checkParamsIsBlank(reqVo.getId())){
            return ResultCode.getFailure(ResultCodeConstant.PARAMS_NOT_EXISTS.getCode(),ResultCodeConstant.PARAMS_NOT_EXISTS.getMessage());
        }
        Menu menu = menuService.getById(reqVo.getId());
        if(menu == null){
            return ResultCode.getFailure("权限不存在");
        }
        menuService.removeById(reqVo.getId());
        logger.warn("用户[{}]删除权限[{}]", getLoginUser().getId()+"-"+getLoginUser().getMobile(), FastJsonUtil.toJsonString(menu));
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/set/sortnum")
    public ResultCode setSortNum(MenuReqVo reqVo){
        if(reqVo == null || checkParamsIsBlank(reqVo.getId())){
            return ResultCode.getFailure(ResultCodeConstant.PARAMS_NOT_EXISTS.getCode(),ResultCodeConstant.PARAMS_NOT_EXISTS.getMessage());
        }
        Menu menu = menuService.getById(reqVo.getId());
        if(menu == null){
            return ResultCode.getFailure("权限不存在");
        }
        menu.setSortNum(reqVo.getSortNum());
        menu.setModifyTime(DateUtil.getCurFullTimestamp());
        menuService.updateById(menu);
        return ResultCode.SUCCESS;
    }

}
